package com.xs.project.service.impl;

import com.aliyuncs.utils.StringUtils;
import com.xs.project.common.Result;
import com.xs.project.mapper.ExamManagerMapper;
import com.xs.project.mapper.ExamTitleMapper;
import com.xs.project.pojo.vo.ExamTitleInsertReq;
import com.xs.project.pojo.vo.ExamTitleReq;
import com.xs.project.pojo.vo.resp.ExamTitleResp;
import com.xs.project.pojo.vo.resp.UserInfoAndCourse;
import com.xs.project.service.ExamTitleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ExamTitleServiceImpl implements ExamTitleService {
    @Resource
    private ExamTitleMapper examTitleMapper;

    @Resource
    private ExamManagerMapper examManagerMapper;
    @Override
    public Result<Boolean> insertTitleExamList(ExamTitleInsertReq request) {
        Integer i = examManagerMapper.selectById(request.getExamId());
        if (i == null || i == 0){
            return Result.fail("考试不存在");
        }
        if (request.getExamType().equals("1")){
            String option = request.getExamOptionA() + "," + request.getExamOptionB() + "," + request.getExamOptionC();
            request.setExamOption(option);
        }
        examTitleMapper.insertTitleExamList(request);
        return Result.success(true);
    }

    @Override
    public Result<List<ExamTitleResp>> selectTitleExamList(ExamTitleReq request) {
        List<ExamTitleResp> list = examTitleMapper.selectTitleExamList(request);
        long skipSize = (long) request.getPageSize() * (request.getPageNum() - 1); // 计算需要跳过的元素数量

        List<ExamTitleResp> pageRes = list.stream()
                .skip(skipSize)
                .limit(request.getPageSize())
                .collect(Collectors.toList());
        for (ExamTitleResp pageRe : pageRes) {
            if ("0".equals(pageRe.getExamType())){
                pageRe.setExamTypeStr("选择题");
            }else {
                pageRe.setExamTypeStr("问答题");
            }
            if (StringUtils.isEmpty(pageRe.getExamOption())){
                continue;
            }
            String[] split = pageRe.getExamOption().split(",");
            pageRe.setExamOptionA(split[0]);
            pageRe.setExamOptionB(split[1]);
            pageRe.setExamOptionC(split[2]);
        }
        return Result.success(pageRes,list.size());
    }

    @Override
    public Result<Boolean> updateTitleExamList(ExamTitleInsertReq request) {
        if (request.getExamType().equals("1")){
            String option = request.getExamOptionA() + "," + request.getExamOptionB() + "," + request.getExamOptionC();
            request.setExamOption(option);
        }
        examTitleMapper.updateTitleExamList(request);
        return Result.success(true);
    }

    @Override
    public Result<Boolean> delTitleExamList(Integer id) {
        examTitleMapper.delTitleExamList(id);
        return Result.success(true);
    }
}
